package cn.wh.job;

import cn.wh.utils.DBUtils;
import cn.wh.utils.DateUtils;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Map;

/**
 * 执行任务，提取MySQL中的Mr数据并插入到Oracle中
 */
public class MrAnalysisJob implements Job {
    // 任务开关
    private static boolean job_switch = false;
    // 每页条数
    private static final int PAGE_TOTAL = 1000;
    private static final Logger LOGGER = LoggerFactory.getLogger(MrAnalysisJob.class.getName());

    // 查询MySQL中Mr数据的Sql
    private static final String queryMySqlMrSql = "select ue_id,neid,serv_cell_ci ,count(1) as count ,min(serv_ecio) as min_serv_ecio,min(serv_rscp_dbm) as min_serv_rscp_dbm,  " +
            "sum(case WHEN serv_rscp_dbm>-90  THEN 1  else 0 end ) gt90 ,  " +
            "sum(case WHEN serv_rscp_dbm>-100  and serv_rscp_dbm<-90  THEN 1  else 0 end ) gt100 ,   " +
            "sum(case WHEN serv_rscp_dbm<-100  THEN 1  else 0 end ) lt100    " +
            "from mr_intrainterfreq   ";

    /**
     * 执行任务
     */
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        if(job_switch){
            LOGGER.error("MrAnalysisJob任务正在执行中无法再次执行。");
            return;
        }
        // 打开任务开关
        job_switch=true;
        long beginJobTime = System.currentTimeMillis();
        if(LOGGER.isDebugEnabled()){
            LOGGER.debug(" MrAnalysisJob 任务开始执行 Runing time:{}", DateUtils.getCurrentTime(null));
        }
        String sb = queryMySqlMrSql + "where  time_s>=STR_TO_DATE('" + "2018-07-17 00:00:00" + "','%Y-%m-%d %H:%i:%s') " +
                " and time_s<=STR_TO_DATE('" + "2018-07-17 23:59:59" + "','%Y-%m-%d %H:%i:%s') and ue_id is not null " +
                " group by ue_id,neid,serv_cell_ci  ";
        //  + " limit 0,100 "
        String countSql = " select count(*)  from ("+sb+") s ";
        int count = DBUtils.queryCountSql(countSql,DBUtils.getMySqlConnection());
        if(count<=0){
            LOGGER.error("当前时间:{} 数据为count:{}",DateUtils.getCurrentTime(null),count);
            return;
        }
        if(LOGGER.isDebugEnabled()){
            LOGGER.debug("当前时间:{} 查询到的数据总数为count:{}",DateUtils.getCurrentTime(null),count);
        }
        int frequency = count%PAGE_TOTAL==0?count/PAGE_TOTAL:count/PAGE_TOTAL+1;
        for (int i = 0; i < frequency; i++) {
            List<Map<String,String>> mapList = DBUtils.querySql(sb+"limit "+i*PAGE_TOTAL+" , "+PAGE_TOTAL,DBUtils.getMySqlConnection());
            DBUtils.insertMrAnalysis(mapList,"2018-07-17");
        }
        long endJobTime = System.currentTimeMillis();
        // 关闭任务开关
        job_switch=false;
        if(LOGGER.isDebugEnabled()){
            LOGGER.debug("Exit MrAnalysisJob 任务执行完成 Runing time:{},totalTime:{}", DateUtils.getCurrentTime(null),endJobTime-beginJobTime);
        }
    }
}
